use sea_orm::Statement;
use sea_orm_migration::prelude::*;

use crate::m20220101_000001_create_table;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(Document::Table)
                    .if_not_exists()
                    .col(ColumnDef::new(Document::Id).string().string_len(20).primary_key())
                    .col(ColumnDef::new(Document::Name).string_len(128).string())
                    .col(ColumnDef::new(Document::ContentText).text())
                    .col(ColumnDef::new(Document::CreatedAt).big_integer())
                    .col(ColumnDef::new(Document::UpdatedAt).big_integer())
                    .to_owned()
            )
            .await?;

            
        let db = manager.get_connection();
        let stmt = Statement::from_string(
            manager.get_database_backend(),
            r#"INSERT INTO `document` (`id`, `name`, `content_text`) select `id`, `title` as `name`, `text` as `content_text` from `post`;"#,
        );
        db.execute(stmt).await?;
        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager.drop_table(Table::drop().table(m20220101_000001_create_table::Post::Table).to_owned()).await?;
        Ok(())
    }
}

#[derive(DeriveIden)]
pub enum Document {
    Table,
    Id,
    Name,
    ContentText,
    CreatedAt,
    UpdatedAt,
}
